<template>
  <div class="container">
    <div class="header">
      <h1>编辑周刊</h1>
    </div>
    
    <el-card class="form-card" v-loading="loading">
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px" 
        class="weekly-form"
      >
        <el-form-item label="标题" prop="weekly_title">
          <el-input v-model="form.weekly_title" placeholder="请输入周刊标题" />
        </el-form-item>
        
        <el-form-item label="PDF文件" prop="file_url">
          <el-upload
            class="pdf-uploader"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            accept=".pdf"
            :on-change="handlePdfChange"
            :before-upload="beforePdfUpload"
            :file-list="fileList"
          >
            <el-button type="primary">更换PDF文件</el-button>
            <template #tip>
              <div class="el-upload__tip">请上传PDF格式文件</div>
            </template>
          </el-upload>
          <div v-if="uploadProgress > 0 && uploadProgress < 100" class="upload-progress">
            <el-progress :percentage="uploadProgress" />
          </div>
          <div v-if="pdfFile" class="pdf-preview-info">
            <span>已选择新文件: {{ pdfFile.name }}</span>
            <el-button type="primary" size="small" @click="previewLocalFile" :disabled="!pdfFileUrl">预览</el-button>
          </div>
          <div v-else-if="form.file_url" class="pdf-current-info">
            <span>当前文件: {{ form.file_url.split('/').pop() || '周刊文件.pdf' }}</span>
            <el-button type="primary" size="small" @click="previewFile">预览</el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="描述" prop="weeklt_description">
          <el-input 
            v-model="form.weeklt_description" 
            type="textarea" 
            :rows="5" 
            placeholder="请输入周刊描述"
          />
        </el-form-item>
        
        <el-form-item label="点赞数">
          <el-input-number v-model="form.like_numbers" :min="0" :precision="0" :step="1" disabled />
          <small class="text-muted">(此数据不可编辑，由系统自动统计)</small>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 预览对话框 -->
    <el-dialog v-model="previewVisible" title="周刊预览" fullscreen>
      <iframe :src="previewFileUrl" style="width: 100%; height: 90vh; border: none;"></iframe>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getWeeklyById, updateWeekly, uploadWeeklyPdf } from '@/api/weekly'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const loading = ref(false)
const submitting = ref(false)
const previewVisible = ref(false)
const uploadProgress = ref(0)
const fileList = ref([])
const pdfFile = ref(null)
const pdfFileUrl = ref(null)
const previewFileUrl = ref('')
const weeklyId = route.params.id

const form = reactive({
  id: null,
  weekly_title: '',
  file_url: '',
  weeklt_description: '',
  like_numbers: 0,
  delete_flag: 0
})

const rules = reactive({
  weekly_title: [
    { required: true, message: '请输入周刊标题', trigger: 'blur' }
  ],
  file_url: [
    { required: true, message: '请上传PDF文件', trigger: 'change' }
  ],
  weeklt_description: [
    { required: true, message: '请输入周刊描述', trigger: 'blur' }
  ]
})

// PDF文件上传前的验证
const beforePdfUpload = (file) => {
  const isPDF = file.type === 'application/pdf'
  const isLt20M = file.size / 1024 / 1024 < 20

  if (!isPDF) {
    ElMessage.error('只能上传PDF格式的文件!')
  }
  
  if (!isLt20M) {
    ElMessage.error('文件大小不能超过20MB!')
  }
  
  return isPDF && isLt20M
}

// 处理PDF文件选择
const handlePdfChange = (file) => {
  if (!file || !file.raw) return
  
  if (beforePdfUpload(file.raw)) {
    pdfFile.value = file.raw
    
    // 创建本地预览URL
    const reader = new FileReader()
    reader.onload = (e) => {
      pdfFileUrl.value = e.target.result
    }
    reader.readAsDataURL(pdfFile.value)
  }
}

// 预览本地文件
const previewLocalFile = () => {
  if (pdfFileUrl.value) {
    previewFileUrl.value = pdfFileUrl.value
    previewVisible.value = true
  } else {
    ElMessage.warning('没有可预览的文件')
  }
}

const previewFile = () => {
  if (form.file_url) {
    previewFileUrl.value = form.file_url
    previewVisible.value = true
  } else {
    ElMessage.warning('没有可预览的文件')
  }
}

// 获取周刊详情
const fetchWeeklyDetail = async () => {
  loading.value = true
  try {
    const response = await getWeeklyById(weeklyId)
    if (response.code === 200 && response.data) {
      // 填充表单
      form.id = response.data.id
      form.weekly_title = response.data.weeklyTitle || ''
      form.file_url = response.data.fileUrl || ''
      form.weeklt_description = response.data.weekltDescription || ''
      form.like_numbers = response.data.likeNumbers || 0
      form.delete_flag = response.data.deleteFlag || 0
      
      // 如果有文件URL，设置文件列表显示
      if (form.file_url) {
        const fileName = form.file_url.split('/').pop() || 'weekly-file.pdf'
        fileList.value = [{ name: fileName, url: form.file_url }]
      }
    } else {
      ElMessage.error(response.message || '获取周刊详情失败')
    }
  } catch (error) {
    ElMessage.error('获取周刊详情失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const submitForm = async () => {
  const valid = await formRef.value.validate().catch(() => false)
  
  if (valid) {
    submitting.value = true
    try {
      // 如果有新选择的文件，先上传
      if (pdfFile.value) {
        uploadProgress.value = 10
        const response = await uploadWeeklyPdf(pdfFile.value)
        uploadProgress.value = 80
        
        if (response.code === 200) {
          // 处理返回的文件路径
          const filePath = response.data || response.message
          const pdfPath = filePath ? filePath.replace(/\s+/g, '') : ''
          
          // 构建完整URL
          form.file_url = `http://localhost:8080/api${pdfPath}`
          ElMessage.success('PDF上传成功')
          uploadProgress.value = 100
        } else {
          ElMessage.error(response.message || 'PDF上传失败')
          uploadProgress.value = 0
          submitting.value = false
          return
        }
      }
      
      // 确保ID是数字类型
      if (form.id === null && weeklyId) {
        form.id = parseInt(weeklyId)
      }
      
      console.log('Submitting weekly data:', form)
      const response = await updateWeekly(form)
      if (response.code === 200) {
        ElMessage.success('周刊更新成功')
        router.push('/weekly')
      } else {
        ElMessage.error(response.message || '周刊更新失败')
      }
    } catch (error) {
      ElMessage.error('周刊更新失败')
      console.error(error)
    } finally {
      submitting.value = false
    }
  }
}

const cancel = () => {
  router.push('/weekly')
}

onMounted(() => {
  fetchWeeklyDetail()
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
  
  .header {
    margin-bottom: 20px;
    
    h1 {
      font-size: 24px;
      margin: 0;
    }
  }
  
  .form-card {
    margin-bottom: 20px;
  }
  
  .weekly-form {
    max-width: 600px;
    margin-top: 20px;
  }
  
  .file-actions {
    margin-top: 8px;
  }
  
  .text-muted {
    color: #999;
    margin-left: 10px;
  }
  
  .pdf-uploader {
    margin-bottom: 10px;
  }

  .upload-progress {
    margin: 10px 0;
  }

  .file-url-input {
    margin-top: 10px;
  }
}
</style> 